package com.example.leetcode.leetcode.hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author haitao
 * @date 2021/8/16 7:12 下午
 * <p>
 * -2 -1 2 2 3
 */
public class Solution15 {


    /**
     * 三数之和
     * 找出数组中不重复三元组的三数之和 双指针
     */
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums.length < 3) {
            return new ArrayList<>();
        }
        // 排序，保证不重复
        Arrays.sort(nums);
        for (int first = 0; first < nums.length; first++) {
            // 保证第一个元素不重复
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            int third = nums.length - 1;
            for (int second = first + 1; second < nums.length; second++) {
                // 保证第二个元素不重复
                if (second > first + 1 && nums[second] == nums[second - 1]) {
                    continue;
                }
                while (third > second && nums[first] + nums[second] + nums[third] > 0) {
                    third--;
                }
                // 如果第三个数左移至第二个数相同,说明first+second+third>0，因为数组是有序的，之后second右移三数之后肯定>0,直接跳出循环
                if (second == third) {
                    break;
                }
                if (nums[first] + nums[second] + nums[third] == 0) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[first]);
                    list.add(nums[second]);
                    list.add(nums[third]);
                    result.add(list);
                }
            }
        }


        return result;
    }

    public static void main(String[] args) {
        Solution15 solution15 = new Solution15();
        int[] nums = new int[]{0,0,0,0};
        System.out.println(solution15.threeSum(nums));
    }
}
